package com.lijun.SpringBootJavaFX.controller;

import com.lijun.SpringBootJavaFX.config.MainWindowHandler;
import de.felixroske.jfxsupport.FXMLController;
import javafx.application.Platform;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebEvent;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import netscape.javascript.JSObject;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.net.URL;
import java.util.ResourceBundle;
@FXMLController
public class WebView1Controller implements Initializable{

    @FXML
    private WebView webView1;


    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // TODO Auto-generated method stub
        webView1.prefWidthProperty().bind(MainWindowHandler.getMainWindow().widthProperty());
        final WebEngine webEngine = webView1.getEngine();
        String url = getClass().getResource("/html/index.html").toExternalForm();
        webEngine.load(url);

        webEngine.setJavaScriptEnabled(true);
        //js的alert监听事件
        webEngine.setOnAlert(new EventHandler<WebEvent<String>>() {
            @Override
            public void handle(WebEvent<String> event) {
                String data = event.getData();
                System.out.println("alert:"+data);
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setHeaderText("This is an alert!");
                alert.setContentText(data);
                alert.showAndWait();
            }
        });
        webEngine.getLoadWorker().stateProperty().addListener(
                (ObservableValue<? extends Worker.State> ov, Worker.State oldState,
                 Worker.State newState) -> {
                    if (newState == Worker.State.SUCCEEDED) {
                        //讲本controller对象嵌入html的window对象，作为app对象使用，js中通过app.可以调用此controller中的方法
                        JSObject win = (JSObject) webEngine.executeScript("window");
                        win.setMember("app", this);
                    }
                }
        );
    }

    public void exit(){
        Platform.exit();
    }

    public void saySomething(String something){
        System.out.println("you say:"+something);
    }

    public void commit(String something){
        System.out.println("you say:"+something);
    }

}
